﻿using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using HT.Model;

namespace HT.Persistency
{
    public class EmployeeInfoPersistency
    {
        public static string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\work\\HTWorkflow\\DB\\HTWorkflowDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;";
        private SqlConnection connection = null;
        private SqlCommand sqlCommand = null;
        
        /// <summary>
        /// 获取指定用户的Report Manager
        /// </summary>
        public string GetReportManagerIDByUser(string userId)
        {
            openConnect();
            sqlCommand.CommandText = "select RMID from Employees where ID=@UserID";
            sqlCommand.Parameters.Add("@UserID", SqlDbType.NVarChar, 128);
            sqlCommand.Parameters["@UserID"].Value = userId;
            SqlDataReader dataReader = sqlCommand.ExecuteReader();
            string reportManager = null;

            if (dataReader.Read())
            {
                reportManager = dataReader["RMID"].ToString();
            }

            closeConnect();

            if (null == reportManager)
            {
                return "";
            }
            else
            {
                return reportManager;
            }          
        }

        /// <summary>
        /// 获取任意一个会计的ID
        /// </summary>
        /// <returns></returns>
        public string GetEmployeeWithRole(string role)
        {            
            openConnect();
            sqlCommand.CommandText = "select ID from Employees where Role=@Role";
            sqlCommand.Parameters.Add("@Role", SqlDbType.NVarChar, 2);
            sqlCommand.Parameters["@Role"].Value = role;
            SqlDataReader dataReader = sqlCommand.ExecuteReader();
            string accountantID = null;
            
            if (dataReader.Read())
            {
                accountantID = dataReader["ID"].ToString();
            }

            closeConnect();

            return accountantID;           
        }

        private void openConnect()
        {
            if (connection == null) connection = new SqlConnection(connectionString);
            if (connection.State != ConnectionState.Closed) connection.Close();
            connection.Open();
            sqlCommand = connection.CreateCommand();
        }

        private void closeConnect()
        {
            connection.Close();
        }
    }
}
